package com.imooc.order.controller;

import com.imooc.controller.BaseController;
import com.imooc.enums.OrderStatusEnum;
import com.imooc.enums.PayMethod;
import com.imooc.order.pojo.OrderStatus;
import com.imooc.order.pojo.bo.OrderStatusCheckBO;
import com.imooc.order.pojo.bo.PlaceOrderBO;
import com.imooc.order.pojo.bo.SubmitOrderBo;
import com.imooc.order.pojo.vo.OrderVO;
import com.imooc.order.service.OrderService;
import com.imooc.order.stream.CheckOrderTopic;
import com.imooc.pojo.IMOOCJSONResult;
import com.imooc.pojo.ShopcartBo;
import com.imooc.utils.CookieUtils;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.RedisOperator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author 顾志杰
 */
@Api(value = "订单相关", tags = "订单相关的接口")
@RestController
@RequestMapping("orders")
public class OrdersController extends BaseController {

    private final OrderService orderService;

    private final RedisOperator redisOperator;

    private final CheckOrderTopic orderStatusProducer;

    @Autowired
    public OrdersController(OrderService orderService, RedisOperator redisOperator, CheckOrderTopic orderStatusProducer) {
        this.orderService = orderService;
        this.redisOperator = redisOperator;
        this.orderStatusProducer = orderStatusProducer;
    }


    @ApiOperation(value = "用户下单", notes = "用户下单", httpMethod = "POST")
    @PostMapping("/create")
    public IMOOCJSONResult add(@RequestBody SubmitOrderBo submitOrderBo,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        if (!submitOrderBo.getPayMethod().equals(PayMethod.ALIPAY.type) &&
                !submitOrderBo.getPayMethod().equals(PayMethod.WEIXIN.type)) {
            return IMOOCJSONResult.errorMsg("支付方式不支持");
        }
        /*redis获取购物车*/
        String shopcartJson = redisOperator.get(FOODIE_SHOPCART + ":" + submitOrderBo.getUserId());
        if (StringUtils.isBlank(shopcartJson)) {
            return IMOOCJSONResult.errorMsg("购物数据不正确");
        }

        List<ShopcartBo> shopcartList = JsonUtils.jsonToList(shopcartJson, ShopcartBo.class);
        /*1.创建订单*/
        PlaceOrderBO orderBO = new PlaceOrderBO();
        orderBO.setItems(shopcartList);
        orderBO.setOrder(submitOrderBo);
        OrderVO orderVO = orderService.createOrder(orderBO);
        String orderId = orderVO.getOrderId();

        /*2.创建订单之后移除购物车内已经结算的商品*/
        if (shopcartList != null) {
            shopcartList.removeAll(orderVO.getToBeRemovedShopcatdList());
            redisOperator.set(FOODIE_SHOPCART + ":" + submitOrderBo.getUserId(), JsonUtils.objectToJson(shopcartList));
        }
        /*整合redis之后，完善购物车中的已结算商品清除，并且同步到前端的cookie*/
        CookieUtils.setCookie(request, response, FOODIE_SHOPCART, JsonUtils.objectToJson(shopcartList), true);


        // order status检查
        OrderStatusCheckBO msg = new OrderStatusCheckBO();
        msg.setOrderID(orderId);
        // 可以采用更短的Delay时间, 在consumer里面重新投递消息
        orderStatusProducer.output().send(
                MessageBuilder.withPayload(msg)
                        .setHeader("x-delay", 3600 * 24 * 1000 + 300 * 1000)
                        .build()
        );
        /*3.向支付中心发送当前订单，用于保存支付中心的订单数据*/
        /*TODO 支付中心代码先忽略 等我自己有帐号的时候在说*/

        /*4.略过支付直接修改订单状态*/
        this.notifyMerchantOrderPaid(orderId);
        return IMOOCJSONResult.ok(orderId);
    }


    /**
     * 支付中心通知系统支付成功
     * @param merchantOrderId
     * @return
     */
    @PostMapping("notifyMerchantOrderPaid")
    public Integer notifyMerchantOrderPaid(String merchantOrderId) {
        orderService.updateOrderStatus(merchantOrderId, OrderStatusEnum.WAIT_DELIVER.type);
        return HttpStatus.OK.value();
    }

    /**
     * 轮询订单是否支付成功
     * @param orderId
     * @return
     */
    @PostMapping("getPaidOrderInfo")
    public IMOOCJSONResult getPaidOrderInfo(String orderId) {
        OrderStatus orderStatus = orderService.queryOrderStatusInfo(orderId);
        return IMOOCJSONResult.ok(orderStatus);
    }

}
